/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package treeOfLife;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Pontus
 */
public class LifeTree extends TreeFrame{
    String nodeType, nodeName, info, fil;
    MyNode rot,thisNode;
    Document doc;
    static File file;
    
    public LifeTree(){
    }
    
    @Override
    void initTree(){

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(file);
            doc.getDocumentElement().normalize();
            rot = readNode(doc.getDocumentElement());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        treeModel = new DefaultTreeModel(rot);
	tree = new JTree(treeModel);
        readNode(doc.getDocumentElement(), rot);
        
    }
    public static MyNode readNode(Node node){
           String nodeType = node.getNodeName();
           Attr attr = (Attr)node.getAttributes().item(0);
           String nodeName = attr.getValue();
           String info = node.getFirstChild().getTextContent();
           MyNode rot = new MyNode(nodeType, nodeName, info);
           return rot;
    }
    
    public void readNode(Node node, MyNode parent){
        NodeList nodeLst = node.getChildNodes();
        for (int i = 0; i < nodeLst.getLength(); i++) {
        Node currentNode = nodeLst.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
            nodeType = currentNode.getNodeName();
            Attr attr = (Attr)currentNode.getAttributes().item(0);
            nodeName = attr.getValue();
            info = currentNode.getFirstChild().getTextContent();
            thisNode = new MyNode(nodeType, nodeName, info);
            parent.add(thisNode);
        }
        readNode(currentNode, thisNode);
    }
    }

    void showDetails(TreePath path){
	if (path == null)
	    return;
	MyNode n = (MyNode)path.getLastPathComponent();
        String info = n.toString()+": "+n.getInfo();
	JOptionPane.showMessageDialog(this, info);
    }

    public static void main(String[] args){
        file = new File("liv.xml");
        if(args.length>0) file=new File(args[0]);
	new LifeTree();
    }
}


